#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
//child子进程-写端
void writer(int wfd)
{
    const char*str="Hello father process,I am a child process";
    pid_t pid=getpid();
    int cnt = 0;
    char buffer[128];
    while(1)
    {
        //1//sleep(3);
        sleep(1);
        snprintf(buffer,sizeof(buffer),"message:%s,pid:%d,count:%d\n",str,pid,cnt);
        write(wfd,buffer,sizeof(buffer));
        //char*s='a';
        //write(wfd,&s,1);
        cnt++;
        //printf("cnt:%d\n",cnt);
        //if(cnt==10)
        //{
        //    break;
        //}
        //2//sleep(1);
    }
    //close(wfd);
}
//father父进程读端
void reader(int rfd)
{
    char buff[1024];
    int cnt=1;
    while(1)
    {
        sleep(1);
        ssize_t n=read(rfd,buff,sizeof(buff)-1);
        printf("第%d次读:%s",cnt,buff);
        cnt++;
        if(cnt==5)
        {
            break;
        }
        // if(n>0)
        // {
        //     printf("第%d次读:%s",cnt,buff);
        //     cnt++;
        // }else if(n==0)
        // {
        //     printf("end!!!\n");
        //     break;
        // }else{
        //     printf("异常\n");
        // }
    }
    close(rfd);
}
int main()
{
    int pipefd[2];
    int n=pipe(pipefd);
    if(n<0)
    {
        return 0;
    }
    /*
     *pipefd[0]:r方式
     *pipefd[1]:w方式
     * */
    printf("pipe[0]:%d,pipe[1]:%d\n",pipefd[0],pipefd[1]);
    pid_t id=fork();
    if(id==0)
    {
        //child process
        //w
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }else{
        //father process
        //r
        close(pipefd[1]);
        reader(pipefd[0]);
        //wait(NULL);
        int status=0;
        int rid=waitpid(id,&status,0);
        if(rid==id)
        {
            printf("退出码:%d,退出信号:%d\n",WEXITSTATUS(status),status&0x7F);
        }
    }
    return 0;
}
